<template>
	<view class="container" >
		<view class="search-box">
			<view class="c-input">
				<uni-easyinput
					prefixIcon="search"
					v-model="value"
					placeholder="输入商品关键词"
					@confirm="handleSearch"
					@input="handleInput"
				></uni-easyinput>
			</view>
		</view>
		
		<!--历史搜索-->
		<view class="record" v-if="!value">
			<view class="cr-action">
				<text class="cra-label">热门搜索</text>
			</view>
			<view class="cr-tag">
				<view class="crt-item" @click="handleTag(item.word)" v-for="item in hotList" :key="item.id">{{ item.word }}</view>
			</view>
			<view class="cr-action">
				<text class="cra-label">历史搜索</text>
				<text class="cra-clear" @click="handleClearRecord">清除历史</text>
			</view>
			<view class="cr-tag">
				<view class="crt-item crt-item-his" v-for="(item,index) in searchRecond" :key="item" @click="handleTag(item)">{{ item }}
				 <u-icon name="close" size="30" @tap.stop="clearHistory(item,index)"></u-icon>
				</view>
			</view>
		</view>
		
		<!--tab-->
		<view class="tabbar" v-if="listVisible">
			<uni-row>
				<uni-col :span="8">
					<view :class="['tab',current === 0 && 'active']" @click="handleTab(0)">
						<text>综合</text>
					</view>
				</uni-col>
				<uni-col :span="8">
					<view :class="['tab',current === 1 && 'active']" @click="handleTab(1)">
						<text>价格</text>
						<u-icon v-if="current === 1" :name="sortType === 1 ? 'arrow-down-fill' : 'arrow-up-fill'" :color="current === 1 && '#CF1A1B'" size="30"></u-icon>
					</view>
				</uni-col>
				<uni-col :span="8">
					<view :class="['tab',(typeIds.length || brandIds.length) && 'active']" @click="modelVisible = true">
						<text>筛选</text>
						<image v-if="!typeIds.length && !brandIds.length" src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/index/icon_filter.png"></image>
						<image v-else src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/index/icon_filter_select.png"></image>
					</view>
				</uni-col>
			</uni-row>
		</view>
		
		<!--列表-->
		<view class="list" v-if="listVisible">
			<view class="list-item" v-for="item of lists" :key="item.goodsId" @click="handleDetail(item.jfcode)">
        <view class="list-item-image">
          <image v-if="item.imgURL" :src="item.imgURL" mode="scaleToFill"></image>
          <image v-else src="@/static/goods_default_square.png" mode="scaleToFill"></image>
          <image class="bage" :src="handleBageDisplay(item.promotionLabel)"></image>
          <view class="tcll-g-markrt" v-if="item.buyPromotion && item.buyPromotion.buyPromotionList && item.buyPromotion.buyPromotionList.length">
            <view class="tcll-gm-left">
              满 <text class="tcll-gml-count">{{ item.buyPromotion.buyNum }}</text> 条
            </view>
            <view class="tcll-gm-right">
              <!-- BUY_GIFT-购物有礼，RAFFLE-购胎抽奖 -->
              <template v-if="item.buyPromotion.buyPromotionList.length === 1">
                <text v-if="item.buyPromotion.buyPromotionList[0].code === 'BUY_GIFT'">享赠品</text>
                <text v-else-if="item.buyPromotion.buyPromotionList[0].code === 'RAFFLE'">享抽奖</text>
              </template>
              <text v-else>享赠品和抽奖</text>
            </view>
          </view>
        </view>
				
				<view class="list-item-info">
					<view class="title">{{ item.name }}</view>
					<view class="tagList" v-if="item.tagList && item.tagList.length">
						<view class="tagList-item" v-for="tag in item.tagList" :key="tag.id">
							{{ tag.name }}
						</view>
					</view>
					<view class="price">
            <view class="price-wrapper" v-if="!item.useCouponPrice">
              <text class="new"><text class="money">¥</text>{{ item.discountShowPrice }}</text>
            </view>
            <view class="price-wrapper" v-else>
              <text class="new-title">券后价</text>
              <text class="new"><text class="money">¥</text>{{ item.useCouponPrice }}</text>
            </view>
            <text class="old">¥{{ item.sellPrice }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<view v-if="emptyVisible" class="empty">
			<image src="@/static/empty2.png"></image>
			<text>没有找到相关的商品信息</text>
			<text>请换一个关键词试试吧</text>
		</view>
		
		<uni-load-more :status="status" v-if="loadVisible"/>
		
		<!--筛选-->
		<u-popup :show="modelVisible" mode="right" @close="modelVisible=false">
			<view class="filter">
				<view class="filter-title">
					<text>筛选条件</text>
					<uni-icons type="closeempty" size="20" @click="modelVisible=false"></uni-icons>
				</view>
				<scroll-view class="filter-box" scroll-y="true">
					<view v-for="filter of filterList" :key="filter.flag">
						<view class="title">{{ filter.title }}</view>
						<view class="content">
							<view :class="['text',item.selected && 'select']" v-for="(item,index) in filter.list" :key="index" @click="handleSelect(item,filter.flag)">
								<text v-if="filter.flag === 'type'">{{item.typeName}}</text>
								<text v-else>{{item.name}}</text>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="filter-button">
					<u-button text="重置" @click="getFilterList"></u-button>
					<u-button text="确认" color="#CF1A1B" @click="handleSubmit"></u-button>
				</view>
			</view>
		</u-popup>
		
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				value: '',
				sortType: 0, // 0-默认按上架时间排序,1-价格降序,2-价格升序
				searchRecond: [], // 搜索历史
				current: 0,
				lists: [],
				page: 1,
				size: 6,
				total: 0,
				status: 'more',
				listVisible: false,
				loadVisible: false,
				emptyVisible: false,
				modelVisible: false,
				filterList: [],
				typeIds: [],
				brandIds: [],
				userInfo: {},
				hotList:[],
			};
		},
    
		onShow(){
			this.loadVisible = false
			this.userInfo = uni.getStorageSync('userInfo')
			const searchRecond = uni.getStorageSync('searchRecond');
			if(searchRecond){
				this.searchRecond = JSON.parse(searchRecond)
			}
			this.getFilterList()
			this.getHotWordList()
		},
		onReachBottom() {
			if(this.lists.length >= this.total) {
				this.status = 'noMore'
				return
			}
			this.loadVisible = true
			this.status = 'loading'
			this.page++ 
			this.getGoodsList()
		},
		onPullDownRefresh() {
			this.loadVisible = false
			this.page = 1
			this.lists = []
			this.getGoodsList()
		},
		methods: {
      handleBageDisplay(data) {
        if(!data.length) {
          return false
        }
        const hasA = data.some((item) => item.code === "DISCOUNT")
        const hasB = data.some((item) => item.code === "POINT")
        
        if (hasA && hasB) {
          return "https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/care/goods_discount_point.png" 
        } else if (hasA) {
          return "https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/care/goods_discount.png" 
        } else if (hasB) {
          return "https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/care/goods_point.png"; 
        } else {
          return ""
        }
      },
			handleTab(flag) {
				this.current = flag
				if(flag === 1) {
					this.sortType = this.sortType === 0 ? 1 : this.sortType === 1 ? 2 : 1
				} else {
					this.sortType = 0
				}
				this.page = 1
				this.lists = []
				this.getGoodsList()
			},
			async getGoodsList() {
				uni.showLoading({
				  title: '加载中...'
				})
				try{
					const res = await this.$request({
						method: 'GET',
						url: '/product-center/merchantPurchase/new/pageGoodsByDriver',
						data: {
							userId: this.userInfo.id || '',
							keyword: this.value,
							sortType: this.sortType,
							brandId: this.brandIds.toString(), // 品牌id
							firstItemTypeId: this.typeIds.toString(), // 商品类别id
							pageNum: this.page,
							pageSize: this.size
						}
					})
					
					this.lists = this.lists.concat(res.datas.data)
					this.total = res.datas.count
					this.loadVisible = this.total > 6
					this.emptyVisible = this.total === 0
					uni.hideLoading()
					uni.stopPullDownRefresh()
				}catch(e){
					uni.hideLoading()
					this.$refs.uToast.show({
						message: e.respMsg,
						type: 'error'
					})
				}
			},
			handleClearRecord(){
				if(this.searchRecond.length){
					uni.showModal({
						content: '确认删除搜索历史吗?',
						confirmText: "确认",
						cancelText: "取消",
						success: res => {
							if(res.confirm){
								this.searchRecond = []
								uni.setStorageSync('searchRecond', JSON.stringify([]));
							}
						}
					})
				}
			},
			handleInput(){
				if(!this.value){
					this.listVisible = false
					this.loadVisible = false
					this.emptyVisible = false
					this.current = 0
				}
			},
			handleSearch() {
				if(!this.value){
					return
				}
				// 缓存到本地
				if(this.searchRecond.length){
					const index = this.searchRecond.indexOf(this.value)
					if(index !== -1){
						this.searchRecond.splice(index, 1)
					}
				}
				this.searchRecond.unshift(this.value)
				uni.setStorageSync('searchRecond', JSON.stringify(this.searchRecond));
				
				// 展示列表
				this.listVisible = true
				this.$nextTick(() =>{
					this.page = 1
					this.lists = []
					this.getGoodsList()
				})
			},
			handleTag(item){
				this.value = item
				this.$nextTick(() =>{
					this.handleSearch()
				})
			},
			handleDetail(code) {
				uni.navigateTo({
				    url: `/components/goodsDetail?jfcode=${code}`
				});
			},
			async getHotWordList() {
				const res = await this.$request({
					method: 'post',
					url: '/terminal-serve-center/search/hotWord/page',
					data:{
						wordType:1,
						pageNum:1,
						pageSize:10
					}
				})
				this.hotList = res.datas.data
			},
			async getFilterList() {
				const res = await this.$request({
					method: 'GET',
					url: '/product-center/merchantPurchase/screen'
				})
				this.filterList = [{
					title: '类型',
					flag: 'type',
					list: res.datas.typeList
				},{
					title: '品牌',
					flag: 'brand',
					list: res.datas.brandList
				}]
				this.typeIds = []
				this.brandIds = []
			},
			handleSelect(item,flag) {
				if(flag === 'type') {
					if (this.typeIds.includes(item.typeId)) {
						item.selected = false
						this.typeIds = this.typeIds.filter(i => i !==item.typeId)
					} else {
						item.selected = true
						this.typeIds.push(item.typeId)
					}
				} else {
					if (this.brandIds.includes(item.brandId)) {
						item.selected = false
						this.brandIds = this.brandIds.filter(i => i !==item.brandId)
					} else {
						item.selected = true
						this.brandIds.push(item.brandId)
					}
				}
			},
			handleSubmit() {
				this.modelVisible = false
				this.page = 1
				this.lists = []
				this.getGoodsList()
			},
			clearHistory(val,index){
				this.searchRecond.splice(index,1)
				uni.setStorageSync('searchRecond', JSON.stringify(this.searchRecond));
			}
		},
	}
</script>

<style lang="scss" scoped>
.active {
	color: #CF1A1B !important;
}
.select {
	color: #FFFFFF;
	background: #CF1A1B !important;
}
.container {
	box-sizing: border-box;
	min-height: 100vh;
	background-color: #ffffff !important;
	overflow: hidden;
	.search-box {
		height: 44px;
		.c-input {
			height: 44px;
			position: fixed;
			// top: 10rpx;
			z-index: 10;
			width: 100%;
			padding: 6rpx 32rpx 0;
			background-color: #ffffff;
			box-sizing: border-box;
		}
	}
	
	.record {
		margin-top: 20px;
		padding: 0 44rpx;
		.cr-action {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 16px;			
			.cra-clear {
				font-size: 12px;
				color: $uni-primary;
			}
		}
		.cr-tag {
			margin-top: 34rpx;
			// display: flex;
			.crt-item {
				display: inline-block;
				font-size: 14px;
				padding: 18rpx 30rpx;
				background: #F5F5F5;
				border-radius: 4rpx;
				margin: 0 32rpx 32rpx 0;
				position: relative;
				/deep/ .u-icon{
					position: absolute;
					padding: 4rpx;
					top: 18rpx;
					right: 8rpx;
				}
			}
			.crt-item-his{
				padding-right: 50rpx;
			}
		}
	}
	
	.tabbar {
		width: 100%;
		position: fixed;
		/deep/ .uni-row {
			height: 44px;
			width: 100%;
			display: flex;
			align-items: center;
			background-color: #FFFFFF;
			border-bottom: 1px rgba(0,0,0,0.08) solid;
		}
		.tab {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: rgba(0,0,0,0.65);
			image {
				width: 16px;
				height: 16px;
			}
		}
	}
	
	.list {
		width: 100%;
		margin-top: 60px;
		&-item {
			margin: 32rpx;
			display: flex;
			padding-bottom: 20rpx;
			border-bottom: 1px rgba(0,0,0,0.08) solid;
      .list-item-image {
        position: relative;
        image {
          width: 88px;
          height: 88px;
          border-radius: 12rpx;
        }
        .bage {
          position: absolute;
          width: 34rpx;
          height: 34rpx;
          right: 0;
          top: 0;
        }
        .tcll-g-markrt {
          position: absolute;
          left: 0;
          bottom: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 9px;
          color: #ffffff;
          background-color: #FB003D;
          height: 34rpx;
          width: 100%;
          font-weight: bold;
          letter-spacing: 1px;
          .tcll-gm-right {
            background: linear-gradient(153deg, #FEFAE7 0%, #FFD938 100%);
            -webkit-background-clip: text; 
            -webkit-text-fill-color: transparent; 
          }
        }
			}
			&-info {
				width: calc(100% - 104px);
				padding-left: 24rpx;
				display: flex;
				flex-direction: column;
				.title {
					font-size: 30rpx;
					color: rgba(0,0,0,0.85);
					overflow:hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					-o-text-overflow:ellipsis;
				}
				.good {
					font-size: 24rpx;
					line-height: 20px;
					color: rgba(0,0,0,0.35);
				}
				
				.tagList {
					display: flex;
					flex-wrap: wrap;
					max-height: 68rpx;
					overflow: hidden;
					margin: 12rpx 0;
				
					.tagList-item {
						margin: 0 16rpx 8rpx 0;
						padding: 0 4rpx;
						font-size: 22rpx;
						color: #996C00;
						background-color: #FFF8E6;
					}
				}
				
				.price {
					line-height: 30px;
          .price-wrapper {
            display: inline;
          } 
          .new-title {
            font-size: 13px;
            color: #EE3B3B;
            margin-right: 8rpx;
          }
					.new {
						font-size: 16px;
						font-weight: bold;
						color: #EE3B3B;
						margin-right: 10rpx;
						.money {
							font-size: 10px;
						}
					}
					.old {
						font-size: 10px;
						color: rgba(#000000, .45);
						line-height: 28rpx;
						text-decoration: line-through;
					}
				}
				.discount {
					display: flex;
					align-items: center;
					.desc {
						margin: 0 20rpx;
						font-size: 26rpx;
						line-height: 26px;
						color: rgba(#000000, .45);
					}
					.num {
						color: #CF1A1B;
					}
				}
			}
		}
	}
	
	.empty {
		width: 100%;
		height: 80%;
		padding-top: 60px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		image {
			width: 220px;
			height: 180px;
		}
		text {
			font-size: 30rpx;
			color: rgba(0,0,0,0.45);
			line-height: 30rpx;
		}
	}
	
	.filter {
		width: 300px;
		&-title {
			width: calc(100% - 32px);
			height: 40px;
			padding: 0 17px;
			line-height: 40px;
			font-size: 32rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			color: rgba(0, 0, 0, 0.85);
			justify-content: space-between;
		}
		&-box {
			flex: 1;
			position: absolute;
			top: 50px;
			right: 16px;
			bottom: 70px;
			left: 16px;
			.title {
				line-height: 30px;
				font-size: 28rpx;
				font-weight: 500;
				color: rgba(0,0,0,0.65);
			}
			.content {
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				.text {
					background: #F2F2F2;
					font-size: 14px;
					padding: 18rpx 30rpx;
					border-radius: 4rpx;
					word-break: break-all;
					margin: 0 32rpx 32rpx 0;
					width: 16%;
				}
			}
		}
		&-button {
			position: absolute;
			height: 70px;
			width: 100%;
			bottom: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #FFFFFF;
			/deep/ .u-button {
				width: 40% !important;
			}
		}
	}
}
</style>
